<template>
	<view class="content">
		<ZPaging ref="paging" v-model="list" :auto="false" :auto-show-system-loading="true"
			loading-more-no-more-text="沒有更多了" loading-more-default-text="點擊加載更多" loading-more-loading-text="正在加載..."
			loading-more-fail-text="加載失敗,點擊重新加載" empty-view-text="沒有數據哦~" refresher-default-text="繼續下拉刷新"
			refresher-pulling-text="鬆開立即刷新" refresher-refreshing-text="正在刷新" empty-view-reload-text="重新加載"
			empty-view-error-text="加載失敗" @query="queryList">
			<template #top>
				<NavBar :title="info.title" :autoBack="false" id="nav">
					<template #left>
						<view class="navbar-left center" @click="goBack">
							<u-icon name="arrow-left" color="#007aff" size="34"></u-icon>
							<text class="c007aff">專案列表</text>
						</view>
					</template>
					<template #right>
						<view class="navbar-right center">
							<text class="c007aff" @click="viewLog">日誌</text>
							<u-icon v-if="userinfo.ident===1" class="ml-20" name="plus" color="#007aff" size="34"
								@click="toPage('AddTask',{id:info.id,type:'list'})"></u-icon>
						</view>
					</template>
				</NavBar>
				<view class="flex totalprogress">
					<view class="bold f32 label">總進度</view>
					<view class="flex val">
						<view class="pro">
							<u-line-progress :show-percent="false" height="8" active-color="#007aff"
								inactive-color="#fac42e" :percent="info.progress"></u-line-progress>
						</view>
						<text class="end txt f26">{{info.progress}}%</text>
					</view>
				</view>
			</template>
			<template #default>

				<view class="list">
					<view class="widths">
						<view v-for="(v,k) in list" :key="k">
							<u-swipe-action v-if="v.ident==1" :show="v.show" :index="k" :options="options"
								:disabled="v.disabled" @open="open" @click="swipeAction">
								<view class="mt-30 item" @click.stop="toPage('StepTwo',{id:v.id})">
									<view class="c007aff bold f30 mb-20 name title-name">
										<text>
											<text>{{v.title}}</text>
											<text class='t1'>工程費用：{{v.totalPrice}}</text>
										</text>
										<text class="title-name-btn">
											<text class="s1" v-if="k!==0" @click.stop="moveUp(v,k)">上移</text>
											<text v-if="k!==list.length-1" @click.stop="moveDown(v,k)">下移</text>
										</text>
									</view>
									<view class="start time" v-if="v.start && v.end">
										<text>{{v.start}}-{{v.delay==0?v.end:v.actualT}}</text>
										<text class="ml-10 f24 c007aff"
											v-if="v.delay != 0">{{v.delay>0?'延遲':'提前'}}{{v.delay}}天</text>
									</view>
									<view class="btns">
										<view v-if="v.casezy_form_template_id" class="btn"
											@click.stop="deleteModule(v,'module')">
											刪除模板
										</view>
										<view v-if="!v.casezy_form_template_id" class="btn"
											@click.stop="showSetPopup(v)">
											設置模板
										</view>
										<view v-if="v.casezy_form_template_id" class="btn"
											@click.stop="toEditTemplate(v)">
											編輯模板
										</view>
										<view v-if="v.casezy_form_template_id"
											@click.stop='toAnswer(v)' class="btn">
											填寫檢查表
										</view>
										<view v-if="v.casezy_form_template_result_id" @click.stop='toDetailr(v)'
											class="btn">
											查看檢查表
										</view>
										<view v-if="v.casezy_form_template_result_id" @click.stop='toDeleteAnswer(v)'
											class="btn">
											删除检查表
										</view>
									</view>
									<view class="flex progress">
										<view class="val">
											<u-line-progress :show-percent="false" height="8" active-color="#fac42e"
												inactive-color="#f1f1f1" :percent="v.progress"></u-line-progress>
										</view>
										<view class="lebel">
											{{v.progress}}%
										</view>
									</view>
								</view>
							</u-swipe-action>
							<view v-else class="mt-30 item" @click.stop="toPage('StepTwo',{id:v.id})">
								<view class="c007aff bold f30 mb-20 name">
									<text>
											<text>{{v.title}}</text>
											<text class='t1'>工程費用：{{v.totalPrice}}</text>
										</text>
								</view>
								<view class="start time" v-if="v.start && v.end">
									<text>{{v.start}}-{{v.delay==0?v.end:v.actualT}}</text>
									<text class="ml-10 f24 c007aff"
										v-if="v.delay != 0">{{v.delay>0?'延遲':'提前'}}{{v.delay}}天</text>
								</view>
								<view class="btns">
									<view v-if="v.casezy_form_template_id && v.ident!=3"
										@click.stop='toAnswer(v)' class="btn">
										填寫檢查表
									</view>
									<view v-if="v.casezy_form_template_result_id && v.ident!=3" @click.stop='toDetailr(v)'
										class="btn">
										查看檢查表
									</view>
								</view>
								<view class="flex progress">
									<view class="val">
										<u-line-progress :show-percent="false" height="8" active-color="#fac42e"
											inactive-color="#f1f1f1" :percent="v.progress"></u-line-progress>
									</view>
									<view class="lebel">
										{{v.progress}}%
									</view>
								</view>
							</view>
						</view>
					</view>

				</view>

			</template>
		</ZPaging>
		<!-- 刪除 -->
		<u-modal v-model="delshow" :mask-close-able="true" :show-cancel-button="true" title="確認刪除摘要嗎？"
			content="將會刪除該摘要下的所有數據,刪除后不可恢復" @confirm="delCasezyById"></u-modal>
		<Tabar></Tabar>
		<u-popup v-model="showPopup" border-radius="14" mode="center" width="1000rpx" height="600rpx">
			<view class="popup-content">
				<view class="popup-tips">
					設置檢查表
				</view>
				<view class="content-view">
					<view class="row">
						<view class="label">
							添加方式:
						</view>
						<view class="value">
							<u-radio-group v-model="addType">
								<u-radio v-for="(item, index) in radioList" :key="index" :name="item.key">
									{{item.name}}
								</u-radio>
							</u-radio-group>
						</view>
					</view>
					<view class="row" v-if="addType === 'byAdd'">
						<view class="label">
							是否複製檢查表:
						</view>
						<view class="value">
							<u-radio-group v-model="yesOrNo">
								<u-radio v-for="(item, index) in yesOrNoList" :key="index" :name="item.key">
									{{item.name}}
								</u-radio>
							</u-radio-group>
						</view>
					</view>
					<view class="row" v-if="addType === 'bySelect'||yesOrNo==='1'">
						<view class="label">
							檢查表:
						</view>
						<view class="value">
							<uni-data-select v-model="form_template_id" :localdata="range"
								@change="change"></uni-data-select>
						</view>
					</view>
				</view>
				<view class="popup-btns">
					<view class="btn" @click="showPopup = false">
						取消
					</view>
					<view class="btn" @click="onAddConfirm">
						確定
					</view>
				</view>
			</view>
		</u-popup>
		<uni-popup ref="deletePop" type="dialog">
			<uni-popup-dialog type="warn" cancelText="取消" confirmText="確定" title="提示" content="您確定刪除此模板嗎？"
				@confirm="onDeleteConfirm"></uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="message" type="message">
			<uni-popup-message type="warn" :message="messageTitle" :duration="3000"></uni-popup-message>
		</uni-popup>
		<uni-popup ref="deleteTem" type="dialog">
			<uni-popup-dialog type="warn" cancelText="取消" confirmText="確定" title="提示" content="您確定刪除此檢查表嗎？"
				@confirm="delAnswer"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	import {
		getCaseProgress,
		getCasezylist,
		delCasezy,
		updateCasezySort
	} from "@/api/apis.js"
	import {
		getFormTemList,
		addCasezyTemplate,
		deleteTem,
		deleteResult
	} from "@/api/template.js";
	import NavBar from "@/component/NavBar"
	import Tabar from "@/component/HomeTab"
	import ZPaging from "@/node_modules/z-paging/components/z-paging/z-paging.vue"
	export default {
		components: {
			NavBar,
			ZPaging,
			Tabar
		},
		data() {
			return {
				delshow: false,
				delId: 0,
				curId: 0,
				title: "",
				list: [],
				info: {
					title: "專案範例",
				},
				options: [{
						text: 'Edit',
						style: {
							backgroundColor: '#ccc',
							color: '#fff'
						}
					},
					{
						text: 'Delete',
						style: {
							backgroundColor: '#ff0000',
							color: '#fff'
						}
					}
				],
				addType: 'bySelect',
				radioList: [{
						name: '檢查表庫選擇',
						key: 'bySelect'
					},
					{
						name: '新設置',
						key: 'byAdd'
					},
				],
				yesOrNoList: [{
						name: '是',
						key: '1'
					},
					{
						name: '否',
						key: '2'
					},
				],
				yesOrNo: '1',
				showPopup: false,
				casezy_id: '',
				range: [],
				curItem: null,
				form_template_id: '',
				isPc: false,
				messageTitle:'請選擇檢查表',
				delTemShow:false,
			}
		},
		onShow() {
			const app = getApp();
			this.isPc = app.globalData.isPc
			this.$nextTick(() => {
				if (uni.getStorageSync("islogin")) {
					if (!this.curId) {
						this.$Toast("數據錯誤")
						setTimeout(() => {
							this.toPage("Main")
						}, 1200)
					} else {
						this.reload();
						this.init()
					}

				}
			})

		},
		mounted() {
			this.previousWidth = window.innerWidth;
			this.previousHeight = window.innerHeight;
			window.addEventListener('resize', this.handleResize);
			// this.getListData()
		},
		beforeDestroy() {
			window.removeEventListener('resize', this.handleResize);
		},
		onLoad() {
			if (uni.getStorageSync("islogin")) {
				const {
					id
				} = this.$Route.query
				if (!id) {
					this.$Toast("數據錯誤")
					setTimeout(() => {
						this.toPage("Main")
					}, 1200)
				} else {
					this.curId = id
				}
			} else {
				this.$Toast("請先登錄")
				setTimeout(() => {
					this.toPage("Home")
				}, 1200)
			}

		},
		computed: {
			...mapState(["userinfo"]),
		},
		methods: {
			swipeAction(index, subindex) {
				if (subindex === 0) {
					//to edit
					this.toPage('AddTask', {
						type: 'list',
						model: 'edit',
						id: this.list[index].id
					})
				} else {
					//to delete
					this.delId = this.list[index].id;
					this.delshow = true
				}
			},
			handleResize() {
				const currentWidth = window.innerWidth;
				const currentHeight = window.innerHeight;
				const swipeViews = document.querySelectorAll('.u-swipe-view');
				swipeViews.forEach((swipeView) => {
					swipeView.style.width = `calc(100% + 180px)`;
				});

			},
			loginout() {
				uni.removeStorageSync("uid");
				uni.removeStorageSync("userToken");
				uni.removeStorageSync("ident")
				uni.removeStorageSync("islogin")
				uni.removeStorageSync("name")
				uni.removeStorageSync("tabIndex")
				uni.removeStorageSync('caseid')
				uni.removeStorageSync("fileDir")
				this.$Toast("退出成功")
				setTimeout(() => {
					//跳轉到登錄頁
					this.$navi({
						route: {
							name: 'Home',
						},
					})
				}, 1200)

			},
			open(index) {
				this.list[index].show = true
				this.list.map((v, k) => {
					if (index != k) this.list[k].show = false
				})
			},
			delCasezyById() {
				// delCasezy
				if (this.delId <= 0) {
					return false;
				}
				let data = {
					id: this.delId,
					uid: uni.getStorageSync("uid"),
				}
				delCasezy(data).then((res) => {
					this.$Toast(res.msg)
					setTimeout(() => {
						this.reload()
					}, 1200)
				}).catch((err) => {
					if (err.code === 102) {
						this.$ClearLogin(err.msg)
					} else {
						this.$Toast(err.msg)
					}
				})
			},
			init() {
				//拿取範例信息
				let uid = uni.getStorageSync("uid")
				getCaseProgress({
					id: this.curId,
					uid
				}).then((res) => {
					this.info = res
				}).catch((err) => {
					this.$Errback(err.msg)
				})

			},
			queryList(pageNo, pageSize) {
				let data = {
					pageNo,
					pageSize,
					id: this.curId,
					uid: uni.getStorageSync("uid")
				}
				getCasezylist(data).then((res) => {
					res.map((item) => {
						let ident = uni.getStorageSync("ident")
						if (ident === 1) {
							item.disabled = false
						}
					})
					// let data = res.map(item=>{
					// 	item.ident = 3
					// 	return item
					// })
					this.$refs.paging.complete(res)
				}).catch((err) => {
					if (err.code === 102) {
						this.$ClearLogin(err.msg)
					} else {
						this.$Toast(err.msg)
					}
				})
			},
			viewLog() {
				let caseid = this.curId;
				this.toPage('ViewLog', {
					id: this.curId,
					leftTitle: this.info.title
				})
			},
			reload() {
				this.$refs.paging.reload();
			},
			goBack() {
				uni.navigateBack(-1)
			},
			toPage(name, params = {}) {
				this.$navi({
					route: {
						name,
						params
					},
				})
			},
			showSetPopup(item) {
				if(!this.isPc){
					this.messageTitle = '此操作需要電腦端操作'
					this.$refs.message.open()
					return
				}
				this.curItem = JSON.parse(JSON.stringify(item))
				this.showPopup = true
				this.getListData(item.id)
			},
			// 獲取檢查表列表
			getListData(casezy_id) {
				let params = {
					uid: uni.getStorageSync("uid"),
					casezy_id
				}
				getFormTemList(params).then(res => {
					let resData = res || []
					this.range = resData.map(item => {
						return {
							text: item.form_template_name,
							value: item.form_template_id
						}
					})
				})
			},
			deleteModule(item) {
				this.curItem = item
				this.$refs.deletePop.open()
			},
			//確定刪除
			onDeleteConfirm() {
				deleteTem({
					uid: uni.getStorageSync("uid"),
					casezy_id: this.curItem.id
				}).then(res => {
					this.$refs.paging.reload();
				})
			},
			// 確定添加
			onAddConfirm() {
				if (this.addType === 'byAdd') {
					if(this.yesOrNo ==='1'){
						//複製模版
						if (!this.form_template_id) {
							this.messageTitle = '請選擇要複製的檢查表'
							this.$refs.message.open()
							return
						}
						uni.navigateTo({
							url: `/pages/checkForm/forms?casezy_form_template_id=${this.form_template_id}&casezy_id=${this.curItem.id}&isCopy=true`
						});
					}else{
						uni.navigateTo({
							url: `/pages/checkForm/forms?casezy_id=${this.curItem.id}`
						});
					}
					this.showPopup = false
					
				} else {
					if (!this.form_template_id) {
						this.messageTitle = '請選擇檢查表'
						this.$refs.message.open()
						return
					}
					addCasezyTemplate({
						uid: uni.getStorageSync("uid"),
						casezy_id: this.curItem.id,
						form_template_id: this.form_template_id
					}).then(res => {
						console.log(res)
						this.$refs.paging.reload();
						this.showPopup = false
					})
				}
			},
			// 編輯模板
			toEditTemplate(item) {
				if(!this.isPc){
					this.messageTitle = '此操作需要電腦端操作'
					this.$refs.message.open()
					return
				}
				uni.navigateTo({
					url: `/pages/checkForm/forms?casezy_form_template_id=${item.casezy_form_template_id}&casezy_id=${item.id}`
				});
			},
			// 查看答案
			toAnswer(item) {
				uni.navigateTo({
					url: `/pages/checkForm/answerPage?casezy_form_template_id=${item.casezy_form_template_id}&casezy_id=${item.id}&casezy_form_template_result_id=${item.casezy_form_template_result_id}`
				});
			},
			// 查看答案詳情
			toDetailr(item) {
				uni.navigateTo({
					url: `/pages/checkForm/detailPage?casezy_form_template_result_id=${item.casezy_form_template_result_id}`
				});
			},
			// 刪除答案
			toDeleteAnswer(item) {
				this.$refs.deleteTem.open()
				this.curItem = item
			},
			delAnswer(){
				let data = {
					casezy_form_template_result_id:this.curItem.casezy_form_template_result_id,
					uid: uni.getStorageSync("uid"),
				}	
				deleteResult(data).then(res=>{
					this.$refs.paging.reload();	
				})
			},
			change(e) {
				console.log(e, this.form_template_id)

			},
			moveUp(item, index) {
				if (index === 0) return
				// let temp = JSON.parse(JSON.stringify(item))
				let cur_sort_number = item.sort_number
				let pre_sort_number = this.list[index - 1].sort_number

				item.sort_number = pre_sort_number
				
				let data = {
					casezy_id_1: item.id,
					sort_number_1: pre_sort_number,
					casezy_id_2: this.list[index-1].id,
					sort_number_2: cur_sort_number,
					uid: uni.getStorageSync("uid"),
				}
				this.updateSort(data)
				this.list.splice(index, 1)
				this.list.splice(index-1, 0, item)
				this.list.forEach((item, index) => {
					item.sort_number = index + 1
				})
			},
			moveDown(item, index) {
				if (index === this.list.length - 1) return
				// let temp = JSON.parse(JSON.stringify(item))
				let cur_sort_number = item.sort_number
				let next_sort_number = this.list[index + 1].sort_number

				item.sort_number = next_sort_number
				this.list[index + 1].sort_number = cur_sort_number
				let data = {
					casezy_id_1: item.id,
					sort_number_1: next_sort_number,
					casezy_id_2: this.list[index+1].id,
					sort_number_2: cur_sort_number,
					uid: uni.getStorageSync("uid"),
				}
				this.updateSort(data)
				this.list.splice(index, 1)
				this.list.splice(index+1, 0, item)
				this.list.forEach((item, index) => {
					item.sort_number = index + 1
				})
			},
			// 重新排序
			updateSort(data) {
				this.$Loading()
				updateCasezySort(data).then(res => {
					// this.$refs.paging.reload();
					uni.hideLoading()
					// this.reload()
				}).catch(err => {
					this.$Toast(err.msg||'重新排序失败')
					this.reload()
				}).finally(() => {
					uni.hideLoading()
				})
			},
		}
	}
</script>

<style lang="scss">
	.content {
		min-height: 100vh;
	}

	.totalprogress {
		height: 228rpx;
		background-color: #ffd33b;
		padding: 0 4%;
		padding-top: 88rpx;

		.label {
			width: 100rpx;
			flex-shrink: 0;
		}

		.val {
			width: calc(100% - 120rpx);

			.pro {
				width: calc(100% - 90rpx);
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
				top: 4rpx;
			}

			.txt {
				width: 70rpx;
				flex-shrink: 0;
			}
		}
	}

	.list {
		padding-bottom: 50rpx;

		/deep/ .u-btn-text {
			color: #fff !important;
		}

		.item {
			padding: 0 40rpx;

			.progress {
				.val {
					width: calc(100% - 90rpx);
				}

				.label {
					width: 70rpx;
				}
			}
		}
	}

	.btns {
		display: flex;
		flex-wrap: wrap;
		gap: 12rpx;
		margin: 24rpx 0;

		.btn {
			background: #FFFFFF;
			border-radius: 6px 6px 6px 6px;
			border: 1px solid #3A78FC;
			padding: 12rpx 24rpx;
			color: #3A78FC;
			cursor: pointer;
		}
	}

	.popup-content {
		padding-top: 24rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;

		.popup-tips {
			font-size: 36rpx;
			color: red;
		}

		.content-view {
			padding-top: 60rpx;
			min-height: 434rpx;
			box-sizing: border-box;
			width: 100%;

			.row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 12rpx 100rpx;

				.label {
					margin-right: 24rpx;
					min-width: 5em;
				}

				.value {
					flex: 1;
				}
			}
		}

		.popup-btns {
			display: flex;
			width: 100%;
			border-top: 1px solid #ebedf0;

			.btn {
				width: 50%;
				text-align: center;
				line-height: 88rpx;
				cursor: pointer;

				&:first-child {
					border-right: 1px solid #ebedf0;
					color: #323233;
				}

				&:last-child {
					color: red;
				}
			}
		}
	}

	::v-deep .uni-select__selector-scroll {
		max-height: 80px;
	}

	::v-deep .fixforpc-z-index {
		z-index: 99999;
	}
	.title-name {
		display: flex;
		justify-content: space-between;
		align-items: center;
		.title-name-btn{
			display: flex;
			justify-content: space-between;
			align-items: center;
			text-align: center;
			color: #007aff;
			font-size: 24rpx;
			opacity: 0.8;
			cursor: pointer;
			.s1{
				margin-right: 10px;
			}
		}
	}
	.t1{
		color: #666;
		margin-left: 10px;
		font-size: 28rpx;
		font-weight: nomral;
	}
</style>